package com.education.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.education.realtime.app.BaseAppV1;
import com.education.realtime.bean.UserLoginBean;
import com.education.realtime.common.Constant;
import com.education.realtime.util.AtguiguUtil;
import com.education.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

public class DwsUserUserLoginWindow extends BaseAppV1 {
    public static void main(String[] args) {
        new DwsUserUserLoginWindow().init(3004,"DwsUserUserLoginWindow", Constant.TOPIC_DWD_TRAFFIC_PAGE);
    }
    @Override
    protected void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {

        // 1. 过滤出登录记录
        SingleOutputStreamOperator<JSONObject> filterLoginData = filterLoginData(stream);
        // 2. 找到当日首次登录和回流记录, 封装到pojo
        SingleOutputStreamOperator<UserLoginBean> streamOperator = findFirstLoginAndBack(filterLoginData);
        // 3. 开窗聚合
        SingleOutputStreamOperator<UserLoginBean> aggregateStream = windowAndAggregate(streamOperator);

        // 4. 写出到clickhouse中
        aggregateStream.addSink(FlinkSinkUtil. getClickHouseSink(Constant.CLICKHOUSE_DB,
                "dws_user_user_login_window",UserLoginBean.class));
    }

    private SingleOutputStreamOperator<UserLoginBean> windowAndAggregate(SingleOutputStreamOperator<UserLoginBean> streamOperator) {
        return streamOperator
                .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(new ReduceFunction<UserLoginBean>() {
                    @Override
                    public UserLoginBean reduce(UserLoginBean t1, UserLoginBean t2) throws Exception {
                        t1.setUuCt(t1.getUuCt() + t2.getUuCt());
                        t1.setBackCt(t1.getBackCt() + t2.getBackCt());
                        return t1;
                    }
                },
                        new ProcessAllWindowFunction<UserLoginBean, UserLoginBean, TimeWindow>() {
                            @Override
                            public void process(Context ctx,
                                                Iterable<UserLoginBean> elements,
                                                Collector<UserLoginBean> out) throws Exception {
                                String stt = AtguiguUtil.toDate(ctx.window().getStart(),"yyyy-MM-dd HH:mm:ss");
                                String edt = AtguiguUtil.toDate(ctx.window().getEnd(),"yyyy-MM-dd HH:mm:ss");

                                UserLoginBean bean = elements.iterator().next();
                                bean.setStt(stt);
                                bean.setEdt(edt);
                                bean.setTs(System.currentTimeMillis());
                                out.collect(bean);
                            }
                        }

                );
    }

    private SingleOutputStreamOperator<UserLoginBean> findFirstLoginAndBack(SingleOutputStreamOperator<JSONObject> stream) {
        return stream
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(5))
                                .withTimestampAssigner((jsonObject, l) -> jsonObject.getLong("ts"))
                )
                .keyBy(obj -> obj.getJSONObject("common").getString("uid"))
                .process(new KeyedProcessFunction<String, JSONObject, UserLoginBean>() {
                    private ValueState<String> lastLoginDateState;
                    @Override
                    public void open(Configuration parameters) throws Exception {

                        lastLoginDateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("lastLoginDateState", String.class));
                    }

                    @Override
                    public void processElement(JSONObject obj,
                                               Context ctx,
                                               Collector<UserLoginBean> out) throws Exception {

                        Long ts = obj.getLong("ts");
                        String today = AtguiguUtil.toDate(ts);
                        String lastLoginDate = lastLoginDateState.value();

                        long uuCt = 0;
                        long backCt = 0;

                        if (!today.equals(lastLoginDate)) {
                            // 今天第一次登录
                            uuCt = 1;
                            if (lastLoginDate != null) {  // 表示这个用户曾经登录过
                                //今天第一次登录, 并且曾经登录过, 判断 登录日期是否相差大于7天
                                long todayTs = AtguiguUtil.toTs(today, "yyyy-MM-dd");
                                long lastLoginDateTs = AtguiguUtil.toTs(lastLoginDate, "yyyy-MM-dd");

                                if ((todayTs - lastLoginDateTs) / 1000 / 60 / 60 / 24 > 7) {
                                    backCt = 1;
                                }
                            }
                            lastLoginDateState.update(today);
                        }

                        if (uuCt == 1) {
                            out.collect(new UserLoginBean("", "", backCt,uuCt,ts));
                        }
                    }
                });
    }

    private SingleOutputStreamOperator<JSONObject> filterLoginData(DataStreamSource<String> stream) {
        return stream
                .map(JSON::parseObject)
                .filter(obj -> {
                    String uid = obj.getJSONObject("common").getString("uid");
//                    System.out.println(uid);
                    String lastPageId = obj.getJSONObject("page").getString("last_page_id");
//                    System.out.println(lastPageId);
                    return uid != null && lastPageId == null;
                });
    }
}
